import React, { useState, useEffect, useRef } from 'react';
import { View, Image, StyleSheet, Dimensions, Text, Animated } from 'react-native';

// 屏幕尺寸
const { width, height } = Dimensions.get('window');

// 欢迎页图片资源（可以替换为自己的图片）
const WELCOME_IMAGES = [
  'https://picsum.photos/seed/welcome1/800/1200',
  'https://picsum.photos/seed/welcome2/800/1200',
  'https://picsum.photos/seed/welcome3/800/1200',
  'https://picsum.photos/seed/welcome4/800/1200',
];

interface WelcomeScreenProps {
  // 可选：跳转至主应用的回调函数
  onComplete?: () => void;
  // 可选：轮播时间（毫秒），默认为1000ms
  interval?: number;
}

const WelcomeScreen: React.FC<WelcomeScreenProps> = ({
  onComplete,
  interval = 2000,
}) => {
  // 当前显示的图片索引
  const [currentIndex, setCurrentIndex] = useState(0);
  // 淡入淡出动画
  const fadeAnim = useRef(new Animated.Value(1)).current;
  // 定时器引用
  const timerRef = useRef<number|null>(null);

  // 切换到下一张图片
  const goToNextImage = () => {
    // 先淡出
    Animated.timing(fadeAnim, {
      toValue: 0,
      duration: 300,
      useNativeDriver: true,
    }).start(() => {
      // 淡出完成后更新索引
      setCurrentIndex((prevIndex) => 
        prevIndex === WELCOME_IMAGES.length - 1 ? 0 : prevIndex + 1
      );
      // 再淡入
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 300,
        useNativeDriver: true,
      }).start();
    });
  };

  // 设置定时器，每隔指定时间切换图片
  useEffect(() => {
    timerRef.current = setInterval(goToNextImage, interval);

    // 清理函数
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, [interval]);

  // 渲染指示器
  const renderIndicators = () => {
    return (
      <View style={styles.indicatorsContainer}>
        {WELCOME_IMAGES.map((_, index) => (
          <View
            key={index}
            style={[
              styles.indicator,
              { 
                backgroundColor: currentIndex === index ? '#fff' : 'rgba(255, 255, 255, 0.5)',
                width: currentIndex === index ? 12 : 6
              }
            ]}
          />
        ))}
      </View>
    );
  };

  return (
    <View style={styles.container}>
      {/* 背景图片 */}
      <Animated.Image
        source={{ uri: WELCOME_IMAGES[currentIndex] }}
        style={[styles.image, { opacity: fadeAnim }]}
        resizeMode="cover"
        accessible={true}
        accessibilityLabel="欢迎页图片"
      />
      
      {/* 半透明遮罩，使文字更清晰 */}
      <View style={styles.overlay} />
      
      {/* 欢迎文字 */}
      <View style={styles.textContainer}>
        <Text style={styles.title}>欢迎使用</Text>
        <Text style={styles.subtitle}>探索更多精彩内容</Text>
      </View>
      
      {/* 指示器 */}
      {renderIndicators()}
      
      {/* 跳过按钮 */}
      {(
        <Text 
          style={styles.skipButton}
          onPress={()=>{
            // 跳转到首页
          }}
        >
          跳过
        </Text>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: 'relative',
  },
  image: {
    width,
    height,
    position: 'absolute',
  },
  overlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
  },
  textContainer: {
    position: 'absolute',
    top: height * 0.3,
    left: 0,
    right: 0,
    alignItems: 'center',
  },
  title: {
    fontSize: 32,
    color: 'white',
    fontWeight: 'bold',
    marginBottom: 10,
  },
  subtitle: {
    fontSize: 18,
    color: 'white',
  },
  indicatorsContainer: {
    position: 'absolute',
    bottom: height * 0.2,
    left: 0,
    right: 0,
    flexDirection: 'row',
    justifyContent: 'center',
    gap: 6,
  },
  indicator: {
    height: 6,
    borderRadius: 3,
  },
  skipButton: {
    position: 'absolute',
    top: 40,
    right: 20,
    color: 'white',
    fontSize: 16,
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
    paddingVertical: 6,
    paddingHorizontal: 12,
    borderRadius: 16,
  },
});

export default WelcomeScreen;
